/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.accident.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.koron.accident.domain.AccidentReport;
import com.koron.accident.domain.PeccancyRecord;
import com.koron.accident.service.api.AccidentReportService;
import com.koron.accident.util.BusinessCode;
import com.koron.common.Excel;
import com.koron.common.StaffAttribute;
import com.koron.common.bean.StaffBean;
import com.koron.common.domain.DataBean;
import com.koron.common.permission.SPIAccountAnno;
import com.koron.common.web.Util;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;
import springfox.documentation.annotations.ApiIgnore;

import java.io.File;
import java.io.InputStream;
import java.util.*;

@Api(tags = "accidentReport",description = "事故报告相关接口类")
@RestController
@RequestMapping("/accidentReport")
public class AccidentReportCotroller {
    private final static Logger logger= LoggerFactory.getLogger(AccidentReportCotroller.class);

    @Autowired
    private AccidentReportService reportService;

    @Autowired
    private Util util;

    @ApiOperation(value = "保存事故报告", notes = "accident_report")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id，新增不传，修改必传",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "corpCode", value = "水司code", required = true, dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "accidentBulletinId", value = "事故快报id", required = true, dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "name", value = "事故名称", required = true, dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "accidentType", value = "事件类别", required = true, dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "accidentLevel", value = "严重级别，0一般，1较大，2重大，3特别重大",  dataType = "Integer",paramType = "query"),
            @ApiImplicitParam(name = "departmentCode", value = "事故单位code", required = true, dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "departmentName", value = "事故单位名称", required = true, dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "occurrencePlace", value = "发生地点",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "occurrenceTime", value = "发生时间,格式为：yyyy-MM-dd HH:mm:ss",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "accidentContent", value = "事故经过",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "accidentRescue", value = "事故救援",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "accidentLoss", value = "事故造成的损失",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "eventDirectReason", value = "事故直接原因",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "eventIndirectReason", value = "事故间接原因",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "eventSystemReason", value = "事故系统原因",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "rectificationRequirement", value = "整改要求",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "rectificationDeadline", value = "整改期限,格式为：yyyy-MM-dd",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "completeTime", value = "整改实际完成日期,格式为：yyyy-MM-dd",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "lossWorkingHours", value = "损工时",  dataType = "BigDecimal",paramType = "query"),
            @ApiImplicitParam(name = "remark", value = "备注",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "rectifier", value = "整改负责人code",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "rectifierName", value = "整改负责人名称",  dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "manager", value = "负责人userid", required = true, dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "managerName", value = "负责人名称", required = true, dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "peccancyRecords", value = "违章记录，格式为：[{'id':'1','corpCode':'2','peccancyStaff':'3','peccancyStaffName':'4','peccancyStaffDept':'5','peccancyStaffDeptName':'6','peccancyBehaviour':'7','peccancyDegree':'8'}]",  dataType = "String",paramType = "query")
    }
    )
    @RequestMapping(value = "/save.htm",method = RequestMethod.POST)
    public MessageBean<Integer> save(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, String userCode, @ApiIgnore AccidentReport bean,@RequestParam(required = false) final String  peccancyRecords,
                                     @RequestParam(required = false)final String keepFiles, @RequestParam(required = false)final String delFiles, @RequestParam(required = false)final String keepPdfFiles, @RequestParam(required = false)final String delPdfFiles,
                                     @RequestParam(required = false)final MultipartFile[]files){
        if (user==null){
            List<StaffBean> staffBeanList= (List<StaffBean>) util.staff(userCode,null).getData();
            if (null!=staffBeanList&&staffBeanList.size()>0)
                user=staffBeanList.get(0);
        }
        if (null==user){
            MessageBean<Integer> messageBean=new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LONGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return messageBean;
        }
        bean.setUpdateTime(new Date());
        bean.setUpdateUser(user.getCode());
        bean.setUpdateUserName(user.getName());
        List<PeccancyRecord> peccancyRecordList=new ArrayList<>();
        if (StringUtils.isNotEmpty(peccancyRecords)){
            JSONArray array= JSON.parseArray(peccancyRecords);
            if (array != null && !array.isEmpty()) {
                Iterator<Object> it = array.iterator();
                while (it.hasNext()) {
                    JSONObject json = (JSONObject) it.next();
                    String corpCode=json.getString("corpCode");
                    String peccancyStaff=json.getString("peccancyStaff");
                    String peccancyStaffName=json.getString("peccancyStaffName");
                    String peccancyStaffDept=json.getString("peccancyStaffDept");
                    String peccancyStaffDeptName=json.getString("peccancyStaffDeptName");
                    String peccancyBehaviour=json.getString("peccancyBehaviour");
                    Integer peccancyDegree=json.getInteger("peccancyDegree");
                    PeccancyRecord peccancyRecord=new PeccancyRecord();
                    peccancyRecord.setCorpCode(corpCode);
                    peccancyRecord.setPeccancyStaff(peccancyStaff);
                    peccancyRecord.setPeccancyStaffName(peccancyStaffName);
                    peccancyRecord.setPeccancyStaffDept(peccancyStaffDept);
                    peccancyRecord.setPeccancyStaffDeptName(peccancyStaffDeptName);
                    peccancyRecord.setPeccancyBehaviour(peccancyBehaviour);
                    peccancyRecord.setPeccancyDegree(peccancyDegree);
                    MessageBean<Integer> msg=checkPeccancyRecord(peccancyRecord);
                    if (msg.getCode()==BusinessCode.SUCCESS.getCode()){
                        peccancyRecordList.add(peccancyRecord);
                    }else{
                        return msg;
                    }
                }
            }
        }
        return reportService.save(user,bean,peccancyRecordList,keepFiles,delFiles,keepPdfFiles,delPdfFiles,files);
    }

    @ApiOperation("删除事故快报接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userCode",value = "用户code,pc端不传，app必传",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "id",value = "事故id",required = true,dataType = "String",paramType = "query"),
    })
    @RequestMapping(value = "/delete.htm",method = RequestMethod.POST)
    public MessageBean<Integer> delete(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, String userCode, @RequestParam final String id){
        if (user==null){
            List<StaffBean> staffBeanList= (List<StaffBean>) util.staff(userCode,null).getData();
            if (null!=staffBeanList&&staffBeanList.size()>0)
                user=staffBeanList.get(0);
        }
        if (null==user){
            MessageBean<Integer> messageBean=new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LONGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return messageBean;
        }
        return reportService.delete(user,id);
    }

    @ApiOperation("查询单个事故快报接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "事故id",required = true,dataType = "String",paramType = "query"),
    })
    @RequestMapping(value = "/details.htm",method = RequestMethod.POST)
    public MessageBean<AccidentReport> details(@RequestParam final String id){
        return reportService.queryOne(id);
    }

    @ApiOperation("事故报告列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "corpCode",value = "水司code",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "name",value = "事件名称",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "departmentCode",value = "事发单位",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "accidentType",value = "事故类型",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "page",value = "当前页",required = true,dataType = "int",paramType = "query"),
            @ApiImplicitParam(name = "pageSize",value = "每页条数",required = true,dataType = "int",paramType = "query"),
    })
    @RequestMapping(value = "/list.htm",method = RequestMethod.POST)
    public MessageBean<DataBean<AccidentReport>> list(@RequestParam(required = false) final String corpCode, @RequestParam(required = false) final String name, @RequestParam(required = false) final String departmentCode,
                                                        @RequestParam(required = false) final String accidentType, @RequestParam Integer page, @RequestParam Integer pageSize){
        Integer start=null;
        if (page==null||page<=0){
            page=1;
            if (pageSize==null||pageSize<=0){
                pageSize=15;
            }
        }
        start=(page<=1)?0:(page-1)*pageSize;
        MessageBean<DataBean<AccidentReport>>msg= reportService.list(corpCode,name,departmentCode,accidentType,start,pageSize);
        if (null!=msg.getData())
            msg.getData().setPageNo(page);
        return msg;
    }

    @ApiOperation("获取所有事故报告列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "corpCode",value = "水司code",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "name",value = "事件名称",dataType = "String",paramType = "query"),
    })
    @RequestMapping(value = "/queryAll.htm",method = RequestMethod.POST)
    public MessageBean<List<AccidentReport>> queryAll(@RequestParam(required = false) final String corpCode, @RequestParam(required = false) final String name){
       return reportService.queryAll(corpCode, name);
    }

    private MessageBean<Integer> checkPeccancyRecord(PeccancyRecord bean){
        MessageBean<Integer> msg=MessageBean.create(BusinessCode.SUCCESS.getCode(),BusinessCode.SUCCESS.getDescription(),Integer.class);
//        if (StringUtils.isEmpty(bean.getCorpCode())){
//            msg.setCode(BusinessCode.PECCANCYRECORD_EMPTY_CORPCODE.getCode());
//            msg.setDescription(BusinessCode.PECCANCYRECORD_EMPTY_CORPCODE.getDescription());
//            return msg;
//        }
        if (StringUtils.isEmpty(bean.getPeccancyStaff())||StringUtils.isEmpty(bean.getPeccancyStaffName())){
            msg.setCode(BusinessCode.PECCANCYRECORD_EMPTY_PECCANCYSTAFF.getCode());
            msg.setDescription(BusinessCode.PECCANCYRECORD_EMPTY_PECCANCYSTAFF.getDescription());
            return msg;
        }
        if (StringUtils.isEmpty(bean.getPeccancyStaffDept())||StringUtils.isEmpty(bean.getPeccancyStaffDeptName())){
            msg.setCode(BusinessCode.PECCANCYRECORD_EMPTY_PECCANCYSTAFFDEPT.getCode());
            msg.setDescription(BusinessCode.PECCANCYRECORD_EMPTY_PECCANCYSTAFFDEPT.getDescription());
            return msg;
        }
        if (StringUtils.isEmpty(bean.getPeccancyBehaviour())){
            msg.setCode(BusinessCode.PECCANCYRECORD_EMPTY_PECCANCYBEHAVIOUR.getCode());
            msg.setDescription(BusinessCode.PECCANCYRECORD_EMPTY_PECCANCYBEHAVIOUR.getDescription());
            return msg;
        }
        if (null==bean.getPeccancyDegree()){
            msg.setCode(BusinessCode.PECCANCYRECORD_EMPTY_PECCANCYDEGREE.getCode());
            msg.setDescription(BusinessCode.PECCANCYRECORD_EMPTY_PECCANCYDEGREE.getDescription());
            return msg;
        }
        return msg;
    }


    @ApiOperation("事故报告列表导出接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "corpCode",value = "水司code",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "name",value = "事件名称",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "departmentCode",value = "事发单位",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "accidentType",value = "事故类型",dataType = "String",paramType = "query"),
    })
    @RequestMapping(value = "/exportList.htm", method = RequestMethod.GET)
    public HttpEntity<?> exportList(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, String corpCode, @RequestParam(required = false) final String name, @RequestParam(required = false) final String departmentCode,
                                    @RequestParam(required = false) final String accidentType) {
        if (null == user) {
            return null;
        }
        List<AccidentReport> list = reportService.exportList(user, corpCode, name,departmentCode,accidentType);
        Map<String, Object> map = new HashMap<>();
        map.put("data", list);
        File targetFile = new File("static/excel/accidentReportList.xlsx");
        try {
            InputStream in = getClass().getClassLoader().getResourceAsStream("static/excel/accidentReportList.xlsx");
            FileUtils.copyInputStreamToFile(in, targetFile);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return Excel.createFile("事故报告列表", targetFile, "accidentReportList.btl", map);
    }
}
